﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace CPlase.Internal.Commands
{
    public class SaveInstanceStorageCacheCommand : IRoleEchoCommand
    {
        public string LocalResourceName;
        public Dictionary<string, object> Files = new Dictionary<string, object>();

        public SaveInstanceStorageCacheCommand() { }

        public SaveInstanceStorageCacheCommand(string LocalResourceName)
        {
            this.LocalResourceName = LocalResourceName;
        }

        public SaveInstanceStorageCacheCommand(string LocalResourceName, string Path, string Content)
        {
            this.LocalResourceName = LocalResourceName;
            AddFile(Path, Content);
        }

        public SaveInstanceStorageCacheCommand AddFile(string Path, string Content)
        {
            if (Files == null) Files = new Dictionary<string, object>();
            Files.Add(Path, Content);
            return this;
        }

        public string Command
        {
            get { return this.GetType().AssemblyQualifiedName; }
        }

        public bool Execute()
        {
            foreach (var File in Files)
            {
                if (File.Value is string)
                {
                    InstanceStorage.Save(LocalResourceName, File.Key, (string)File.Value);
                }
            }
            return true;
        }

        public Dictionary<string, string> Serialize()
        {
            return new Dictionary<string, string>()
                {
                    {"files", JsonConvert.SerializeObject(Files)},
                    {"resource", LocalResourceName}
                };
        }

        public void Deserialize(NameValueCollection Params)
        {
            this.LocalResourceName = Params["resource"];
            this.Files = JsonConvert.DeserializeObject<Dictionary<string, object>>(Params["files"]);
        }
    }
}